package com.leimo.demo.jdbc.service;

import com.leimo.demo.jdbc.model.User;
import java.sql.SQLException;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

public class UserServiceImpl implements UserService {

  @Autowired
  private JdbcTemplate jdbcTemplate;

  @Override
  public void createSQL() {
    jdbcTemplate.execute("drop table user");
    jdbcTemplate.execute("create table user(uid integer, name text)");

    jdbcTemplate.execute("drop table address");
    jdbcTemplate.execute("create table address(id integer, address text)");
  }


  @Transactional
  @Override
  public void addUserAll(User user) {
    this.addUser(user);
    User user1 = new User();
    user1.setUid(user.getUid()+1);
    user1.setName("TestDemand");
    this.addUser2(user1);
  }

  @Transactional
  public void addUser(User user) {
    int update = jdbcTemplate
        .update("insert into user(uid, name) values (?, ?)", user.getUid(), user.getName());
    System.out.println("update = " + update);
  }

  @Transactional(propagation = Propagation.MANDATORY)
  public void addUser2(User user) {
    int update = jdbcTemplate
        .update("insert into user(uid, name) values (?, ?)", user.getUid(), user.getName());
    System.out.println("addUser2 update = " + update);
  }

  public List<User> findAll() throws SQLException {
    return jdbcTemplate.query("select uid, name from user", (rs, rowNum) -> {
      User user = new User();
      user.setUid(rs.getInt(1));
      user.setName(rs.getString(2));
      return user;
    });
  }
}
